package com.example.lib_base.base.activity

import android.os.Bundle
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aspsine.swipetoloadlayout.OnLoadMoreListener
import com.aspsine.swipetoloadlayout.OnRefreshListener
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.BaseLoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.lib_base.R
import com.example.lib_base.base.empty.EmptyView
import com.example.lib_base.base.empty.ErrorView
import com.example.lib_base.base.empty.LoadingView
import com.example.lib_base.base.extensions.observeNonNull
import com.example.lib_base.base.util.GsonUtils
import com.example.lib_base.base.vm.BaseRvViewModel
import com.google.gson.JsonParser
import com.zy.multistatepage.MultiStateContainer
import com.zy.multistatepage.state.SuccessState

abstract class BaseRVActivity<B : ViewDataBinding, VM : BaseRvViewModel, T> :
    BaseAppBVMActivity<B, VM>(), OnRefreshListener, OnLoadMoreListener {
    /**
     * 适配器
     */
    abstract fun createAdapter(): BaseQuickAdapter<T, BaseViewHolder>

    /**
     * 数据源参数类型
     */
    abstract fun createClass(): Class<*>

    /**
     * 获取数据
     */
    abstract fun createListData(page: Int)

    /**
     * 缺省页
     */
    var multiStateContainer: MultiStateContainer? = null

    /**
     * 列表控件
     */
    lateinit var mRecyclerView: RecyclerView

    /**
     * 适配器
     */
    lateinit var mAdapter: BaseQuickAdapter<T, BaseViewHolder>

    /**
     * 刷新控件
     */
    var swipeToLoadLayout: SwipeToLoadLayout? = null

    /**
     * 是否是刷新状态
     */
    var isRefresh = true

    /**
     * 页码
     */
    var page = 1

    override fun initialize(savedInstanceState: Bundle?) {
        initViews()
        multiStateContainer?.show<LoadingView> { }
        createListData(page)
    }

    /**
     * 初始化控件
     */
    fun initViews() {
        if (findViewById<RecyclerView>(R.id.swipe_target) != null) {
            mRecyclerView = findViewById(R.id.swipe_target)
        }
        if (findViewById<MultiStateContainer>(R.id.multis) != null) {
            multiStateContainer = findViewById(R.id.multis)
        }
        if (findViewById<SwipeToLoadLayout>(R.id.swipeToLoadLayout) != null) {
            swipeToLoadLayout = findViewById(R.id.swipeToLoadLayout)
            swipeToLoadLayout?.setOnRefreshListener(this)
            swipeToLoadLayout?.setOnLoadMoreListener(this)
            //默认使用自动加载(关闭上拉加载)
            swipeToLoadLayoutSwitch(loadMore = false)
        }
        initAdapter()
        viewModel.listLiveData.observeNonNull(this) {
            var list = mutableListOf<T>()
            try {
                var arr = JsonParser().parse(it).asJsonArray
                arr.forEach { sub ->
                    var data = GsonUtils.getGson().fromJson(sub, createClass())
                    if (data as T != null) {
                        list.add(data)
                    }
                }
            } catch (t: Throwable) {
                println("--------------- 数据解析异常")
            }
            update(list)
        }
    }


    /**
     * 数据源更新
     */
    private fun update(list: MutableList<T>) {

        when {
            isRefresh && list.size == 0 -> {//第一页无数据 显示缺省页
                showEmptyDataView("暂无数据")
            }
            isRefresh && list.size > 0 -> { //第一页有数据 1、刷新数据 2、显示内容页
                mAdapter.setList(list)
                getLoadMoreModule()?.isEnableLoadMore = true
                showContentView()
            }
            !isRefresh && list.size == 0 -> {//加载页无数据 显示页脚
                mAdapter.addFooterView(layoutInflater.inflate(R.layout.not_loading,
                    mRecyclerView.parent as ViewGroup,
                    false))
//                getLoadMoreModule()?.isAutoLoadMore = false
//                getLoadMoreModule()?.isEnableLoadMore = false
                getLoadMoreModule()?.loadMoreEnd(true)

            }
            !isRefresh && list.size > 0 -> {//加载页有数据 刷新适配器
                mAdapter.addData(list)
                getLoadMoreModule()?.loadMoreComplete()
            }
        }
        //关闭刷新
        swipeToLoadLayout?.isRefreshing = false
        //关闭 加载更多
        swipeToLoadLayout?.isLoadingMore = false
    }

    /**
     * 设置RecyclerView相关配置
     */
    fun initRecyclerView(row: Int = 1, color: Long = 0xffffffff) {
        if (row <= 1) {
            mRecyclerView.layoutManager = LinearLayoutManager(this)
        } else {
            var manager = GridLayoutManager(this, row)
            manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return if (position == mAdapter.data.size) row else 1
                }
            }
            mRecyclerView.layoutManager = manager
        }
        mRecyclerView.setHasFixedSize(true)
    }

    /**
     * 设置Adapter相关配置
     */
    private fun initAdapter() {
        mAdapter = createAdapter()
        try {
            mAdapter.loadMoreModule.isAutoLoadMore = true
            mAdapter.loadMoreModule.preLoadNumber = 5
            mAdapter.loadMoreModule.setOnLoadMoreListener {
                //加载更多逻辑
                onLoadMore()
            }
        } catch (t: Throwable) {
            println("-------------------------  自动加载配置异常 $t")
        }
        mRecyclerView.adapter = mAdapter
    }

    fun getLoadMoreModule(): BaseLoadMoreModule? {
        return try {
            mAdapter.loadMoreModule
        } catch (t: Throwable) {
            null
        }
    }

    /**
     * 错误缺省页
     */
    fun showErrorView() {
        multiStateContainer?.show<ErrorView> {
            it.retry() {
                onRefresh()
            }
        }
    }

    /**
     * 无数据缺省页
     */
    fun showEmptyDataView(msg: String) {
        multiStateContainer?.show<EmptyView> {
            it.setEmptyMsg(msg)
        }
    }

    /**
     * 显示内容页
     */
    fun showContentView() {
        multiStateContainer?.show<SuccessState> {
        }
    }

    /**
     * 刷新和加载更多开关
     */
    fun swipeToLoadLayoutSwitch(refresh: Boolean = true, loadMore: Boolean = true) {
        swipeToLoadLayout?.isRefreshEnabled = refresh
        swipeToLoadLayout?.isLoadMoreEnabled = loadMore
    }

    /**
     * 刷新
     */
    override fun onRefresh() {
        mAdapter.removeAllFooterView()
        isRefresh = true
        getLoadMoreModule()?.isEnableLoadMore = false
        page = 1
        createListData(page)
    }

    /**
     * 加载更多
     */
    override fun onLoadMore() {
        isRefresh = false
        page += 1
        createListData(page)
    }
}
